package ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import ssm.myPojo.PerCustom;
import ssm.myPojo.PubCustom;
import ssm.myPojo.SourQueryVo;
import ssm.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class PublicController {

    @Autowired
    private UserService userService;


    @RequestMapping("/home")
    public String home(Model model, SourQueryVo sourQueryVo, HttpSession session){

//        List<PubCustom> pubList;
//        List<String> typeList = new ArrayList<>();
//        try {
//            pubList = userService.findAllPub(sourQueryVo);
//            for(Pub pub:pubList){
//                while(!typeList.contains(pub.getSourcetype())){
//                    typeList.add(pub.getSourcetype());
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        List<String> typeList = null;

        //通过group by 获取所有sourceType
        try {
            typeList = userService.selectAllType();
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("typeList",typeList);

        return "pub/public";
    }

    //相似查询资源
    @RequestMapping("/queryPubByLike")
    public String queryPubByLike(Model model,SourQueryVo sourQueryVo)throws Exception{

        List<PubCustom> pubCustoms = userService.findAllPubByLike(sourQueryVo);

        model.addAttribute("pubCustoms",pubCustoms);

        return "pub/queryPubByLike";
    }

    //根据已有类型查询资源
    @RequestMapping("/ShowByType")
    public String ShowType(Model model,
                       @RequestParam(value = "Type",required = true) String Type){

        List<PubCustom> pubs = null;
        try {
            pubs = userService.findPubByType(Type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("pubs",pubs);
        return "pub/ShowByType";
    }

    //进入资源录入界面,并根据传入的username获取用户id，传入到资源写入界面
    @RequestMapping("/toWrite")
    public String toWrite(Model model,
                          @RequestParam("username") String username,Integer id)throws Exception{

        System.out.println("跳转到资源写入界面");
        //根据用户名获取id
        id = userService.findUserByName(username).getId();
        //传入id
        model.addAttribute("userId",id);
        model.addAttribute("username",username);
        //return "pub/writeIn";
        return "pub/writeIn";
    }

    //资源录入,并对输入的资源进行校验,并通过bindingResult获取校验错误信息
    @RequestMapping("/WriteIn")
    public String writeInPub(Model model,
                             //使用@RequestParam注解获取页面中的参数，括号中的""要和页面的值的name相同，
                             // ********当定义的形参和请求的name相同@RequestParam注解可以不写
                             //@RequestParam("selectId") String selectId,//获取页面的用户Id
                             String selectId,//用于选择保存位置
                             @RequestParam("resource_pic") String sourString,
                             @RequestParam("resource_file") MultipartFile sourfile,
                             // ********当定义的形参和请求的对象的name相同@ModelAttribute注解可以不写
                             //使用@ModelAttribute注解直接将页面中的多个参数注入到对象中，每个参数的name要和对象的属性相同
                             @Validated PubCustom pubCustom, BindingResult bindingResult

    )throws Exception{
        //输出错误
        if(bindingResult.hasErrors()){
            List<ObjectError> objectErrors = bindingResult.getAllErrors();
            //将错误信息输出到控制台
            for(ObjectError objectError:objectErrors){
                System.out.println(objectError.getDefaultMessage());
            }
            //将错误信息传入到原来的页面并输出错误信息
            model.addAttribute("objectErrors",objectErrors);
            return "pub/writeIn";
        }

        //如果是链接资源，存入链接资源
        if(sourString!=null&&sourfile.isEmpty()){
            pubCustom.setResource(sourString);
        }
        //字符串的空判断s == ""或者s.isEmpty(),
        if((!sourfile.isEmpty())&&sourString.isEmpty()){
            //获取图片名称，并创建新的图片名称
            String filename = sourfile.getOriginalFilename();
            String newFileName = UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
            String pic_path;//选择用于存储图片的目录
            if(pubCustom.getSourcetype().equals("文档资源")) {
                pic_path = "E:\\1_毕业论文综合\\资源目录\\sourFile";
            }else{
                pic_path = "E:\\1_毕业论文综合\\资源目录\\sourPic";
            }
            //将图片保存到目录中
            File newfile = new java.io.File(pic_path, newFileName);
            if(!filename.equals("")) {
                if (!newfile.getParentFile().exists()) {
                    newfile.getParentFile().mkdirs();//mkdirs()可以创建多及目录，mkdir()只能创建以及目录
                }
                sourfile.transferTo(newfile);//将图片写入到新创建的文件夹中
            }
            //将图片名存入到对象对应的属性中
            pubCustom.setResource(newFileName);
        }
        //存入file，将file保存在服务器的对象存储OSS中，以key/value方式保存图片,文件

        //写入资源
        if(selectId.equals("pub")) {
            //调用servlet写入资源
            userService.insertIntoPub(pubCustom);
        }else{
            PerCustom perCustom = null;
            perCustom.setId(pubCustom.getId());
            perCustom.setResource(pubCustom.getResource());
            perCustom.setSourcetype(pubCustom.getSourcetype());
            perCustom.setSourcead(pubCustom.getSourcead());
            perCustom.setSourcenote(pubCustom.getSourcenote());
            userService.insertIntoPer(perCustom);
        }

        //返回到主界面
        return "redirect:home";
    }

    //资源下载
    @RequestMapping("/downloadSour")
    public String downloadSour(Model model,
                               HttpServletResponse response,
                               HttpServletRequest request,
                               @RequestParam("sour") String sourcename,
                               @RequestParam("type") String type
    )throws Exception{

        //获取文件名
        //当文件名不是英文名时，需要用url解码器编码一下
        sourcename = URLEncoder.encode(sourcename,"UTF-8");
        //根据图片名获取图片路径
        File file = null;
        if(type.equals("图片资源")) {
            //设置响应类型为图片
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "attachment;filename=" + sourcename);
            file = new File("E:\\1_毕业论文综合\\资源目录\\sourPic", sourcename);
        }
        if(type.equals("文本资源")) {
            //设置响应类型为文本
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment;filename=" + sourcename);
            file = new File("E:\\1_毕业论文综合\\资源目录\\sourFile", sourcename);
        }
        if(file.exists()) {
            //通过IO流传输数据
            InputStream inputStream = new FileInputStream(file);
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            //定义缓冲区大小
            byte[] buff = new byte[4 * 1024];
            int len = 0;
            while ((len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
            //关闭输出流
            inputStream.close();
            outputStream.close();
        }

        return "success";
    }

}
